<template>
  <div class="chatBox" v-if="current != 0 && data[current]">
    <div class="toolsBar">
      <div class="list_switch" @click="selectSwitch(0)" :class="{active: data[current].listswitch === 0}">
        <Icons name="xiazai16" />我的消息
      </div>
      <div class="list_switch" @click="selectSwitch(1)" :class="{active: data[current].listswitch === 1}">
        <Icons name="yonghutouxiang" />联系人
      </div>
      <div class="tongji">
        <div class="item group">已沟通<b title="">{{data[current].statis.groupid || 0}}</b></div>
        <div class="item ungroup">未沟通<b title="">{{data[current].statis.ungroupid || 0}}</b></div>
        <div class="item qg">取关数<b title="">{{data[current].statis.unsubscribe || 0}}</b></div>
        <div class="item qglv">取关率<b title="">{{((data[current].statis.unsubscribe||0) / ((data[current].statis.subscribe||0) + (data[current].statis.unsubscribe||0)) * 100).toFixed(2) + '%'}}</b></div>
      </div>
      <div class="logo" @click="openLink('https://www.haicaochat.com/index.html')">
        <img src="../../assets/images/logo1.png" alt="">
      </div>
      <div class="setting" @click="openSetBox"><Icons name="shezhi" /></div>
      <Modal class="settingbox" @on-visible-change="changeSetBox" v-model="data[current].settingbox.isopen" width="360">
          <p slot="header"><Icons :size="34" name="haicao" />设置</p>
          <div class="settingcont">
            <div class="left">
              <div class="item" @click="selectSetItem(1)" :class="{active: data[current].settingbox.index === 1}">离线回复</div>
              <div class="item" @click="selectSetItem(2)" :class="{active: data[current].settingbox.index === 2}">通用设置</div>
              <div class="item" @click="selectSetItem(3)" :class="{active: data[current].settingbox.index === 3}">关于海草</div>
            </div>
            <div class="right">
              <div class="item reply_msg" :class="{active: data[current].settingbox.index === 1}" v-if="data[current].settingbox.replymsg">
                <div class="replybox">
                  <div class="tit">离线文本回复</div>
                  <textarea v-model="data[current].settingbox.replymsg.reply_text"></textarea>
                </div>
                <div class="replybox">
                  <div class="tit">离线图片回复</div>
                  <div class="showimg" @click="uploadReplypic">
                    <div class="noimg" v-show="!data[current].settingbox.replymsg.reply_img">
                      <Icon type="md-cloud-upload" />
                    </div>
                    <img :src="data[current].settingbox.replymsg.reply_img | formatPicPath"  v-show="data[current].settingbox.replymsg.reply_img">
                  </div>
                </div>
                <div class="replybox timeoutbox">
                   <div class="tit">超时回复设置</div>
                   <div class="settimeout">
                     <div class="isinure">是否开启 <i-switch @on-change="settimeout" size="small" v-model="data[current].settingbox.replymsg.isinure"/> &emsp;&emsp;</div>
                     <div class="timeout">超时时间 <Input @on-blur="settimeout" v-model="data[current].settingbox.replymsg.timeout" size="small" /></div>
                   </div>
                 </div>
                <div class="save" @click="saveReplyMsg">保存</div>
              </div>
              <div class="item config" :class="{active: data[current].settingbox.index === 2}" v-if="config">
                <div class="group_item">
                  <div class="items"><Checkbox @on-change="saveConfig" v-model="config.notifi_sound">开启新消息提示音</Checkbox></div>
                  <div class="items selectmp3" :class="{del: !config.notifi_sound}">
                    <input type="text" v-model="config.newmsg_mp3"/> <a @click="selectNotifiSound('newmsg')">选择</a><a @click="playNotifiSound(config.newmsg_mp3)">预览<Icon type="md-play" /></a><span>(新消息提示音)</span>
                  </div>
                  <div class="items selectmp3" :class="{del: !config.notifi_sound}">
                    <input type="text" v-model="config.subscribe_mp3"/> <a @click="selectNotifiSound('subscribe')">选择</a><a @click="playNotifiSound(config.subscribe_mp3)">预览<Icon type="md-play" /></a><span>(新关注提示音)</span>
                  </div>
                  <div class="items selectmp3" :class="{del: !config.notifi_sound}">
                    <input type="text" v-model="config.unsubscribe_mp3"/> <a @click="selectNotifiSound('unsubscribe')">选择</a><a @click="playNotifiSound(config.unsubscribe_mp3)">预览<Icon type="md-play" /></a><span>(取消关注提示音)</span>
                  </div>
                </div>
              </div>
              <div class="item aboutus" :class="{active: data[current].settingbox.index === 3}">
                <!-- <img @click="openLink('https://www.haicaochat.com/index.html')" src="../../assets/images/logo1.png" alt="" class="logo"> -->
                <div class="logo">
                  <Icons name="haicao" />
                </div>
                <div class="info">
                  <p>版本信息: <span @click="openUpdata" :news="newVersion.incheck? 1 : 0" class="showversion">{{version}}</span><a @click="openUpdata" v-if="newVersion.incheck == 1">&emsp;&emsp;&emsp;有新版本</a></p>
                  <a @click="openLink($store.state.Config.base_url.split('/api')[0] + '/getVersion/?type=1002')">查看历史版本</a> <br>
                  <a @click="openLink('https://www.haicaochat.com/index.html')">查看帮助</a>
                </div>
              </div>
            </div>
          </div>
      </Modal>
    </div>
    <div class="listBox">
      <csuserInfo ref="csuser_info" @openMassbox="openMassbox" @setUsetType="setUsetType" :csuser="data[current].csuser" />
      <userList ref="msguser_list" :active="data[current].currentuser" @msg-click="msgClick" :data="data[current].msguser" v-if="data[current].listswitch === 0"/>
      <userList ref="alluser_list" @msg-click="msgClick" type="user" :data="data[current].alluser" v-else-if="data[current].listswitch === 1"/>
    </div>
    <div class="msgBox">
      <massMsg @closeMassbox="closeMassbox" ref="massmsg_box" v-if="data[current].massmsg" :csuser="data[current].csuser" :msguser="data[current].msguser" :userlist="data[current].alluser" class="massMsg" />
      <Spin size="large" fix v-if="data[current].userload"></Spin>
      <chat-window @load-done="chatWindowLoadEnd" @setuserinfo="setUserinfo" @openMassbox="openMassbox" ref="chat_win" v-if="data[current].currentuser" :user="data[current].currentuser" :csId="current" />
      <div class="nomsg" v-show="!data[current].currentuser">
        <Icons name="qingkong" />当前没有聊天
      </div>
    </div>
  </div>
</template>

<script>
import csuserInfo from '../csuserInfo'
import userList from '../userList'
import chatWindow from '../chatWindow'
import massMsg from '../massMsg'
export default {
  name: 'chatBox',
  data () {
    return {
      config: null,
      newVersion: {
        incheck: false,
        data: {}
      },
      defaultpic: require('../../assets/images/timg.jpg'),
      data: {}
    }
  },
  watch: {
    async current (newVal, oldVal) {
      if (!this.data[this.current]) {
        await this.loadingRes(this.current)
        return
      }
      this.data[this.current].msguser && this.data[this.current].msguser.forEach((item) => {
        if (item.user_id === this.data[this.current].currentuser.id) {
          if (item.new_msg_num) {
            item.new_msg_num = 0
            this.$emit('clearNewnum', this.current, {
              id: item.user_id,
              num: item.new_msg_num,
              openid: item.openid
            })
          }
        }
      })
      this.$emit('updataStatus', this.current, {
        listswitch: this.data[this.current].listswitch,
        statis: this.data[this.current].statis
      })
    }
  },
  props: {
    current: {
      default: 0
    }
  },
  components: {
    csuserInfo,
    userList,
    chatWindow,
    massMsg
  },
  async created () {
    window.$chatBox = this
    this.loadingRes(this.current)
    this.$forceUpdate()
  },
  methods: {
    chatWindowLoadEnd () {
      this.data[this.current].userload = false
      this.$forceUpdate()
    },
    // 设置列表显示
    setListShow (csId, index) {
      if (index === 3) {
        return this.openMassbox()
      }
      this.selectSwitch(index)
      this.$emit('updataStatus', csId, {
        listswitch: this.data[csId].listswitch,
        statis: this.data[csId].statis
      })
    },
    // 新消息进入
    newsMsg (msg) {
      if (msg.type === 'subscribe') {
        this.data[msg.cs_id].alluser.forEach((item) => {
          if (item.openid === msg.openid) {
            item.subscribe = 1
            this.data[msg.cs_id].statis = this.calcUsers(this.data[msg.cs_id].alluser)
            this.$forceUpdate()
          }
        })
      } else if (msg.type === 'unsubscribe') {
        this.data[msg.cs_id].alluser.forEach((item) => {
          if (item.openid === msg.openid) {
            item.subscribe = 0
            this.data[msg.cs_id].statis = this.calcUsers(this.data[msg.cs_id].alluser)
            this.$forceUpdate()
          }
        })
      }
    },
    // 打开更新
    openUpdata () {
      if (this.newVersion.incheck) {
        let win = this.$Win.createWin({
          width: 480,
          height: 400,
          transparent: true,
          windowConfig: {
            router: '/updata', // 路由
            animation: 'fromTop',
            name: 'updata',
            data: this.newVersion.data
          }
        })
        win.on('closed', () => { win = null })
        win.show()
      }
    },
    // 在外部浏览器打开链接
    openLink (link) {
      this.$electron.shell.openExternal(link)
    },
    // 播放提示音
    playNotifiSound (path) {
      var audio = document.createElement('audio')
      audio.src = path
      audio.setAttribute('autoplay', 'true')
    },
    // 选择提示音
    selectNotifiSound (type) {
      var selectInput = document.createElement('input')
      selectInput.setAttribute('type', 'file')
      selectInput.setAttribute('accept', '*.mp3')
      var _this = this
      selectInput.onchange = function () {
        if (this.files[0].type !== 'audio/mp3') return _this.$Message.error('请选择MP3格式的音频')
        var path = this.files[0].path
        if (type === 'newmsg') {
          _this.config.newmsg_mp3 = path
        } else if (type === 'subscribe') {
          _this.config.subscribe_mp3 = path
        } else if (type === 'unsubscribe') {
          _this.config.unsubscribe_mp3 = path
        }
        _this.saveConfig()
        _this.playNotifiSound(path)
        selectInput = null
      }
      selectInput.click()
    },
    // 保存配置文件
    async saveConfig () {
      try {
        var result = await this.$db.config.setConfig(this.config)
        if (result.status === 1) {
          this.$Message.success('保存成功')
        } else {
          this.$Message.error('保存配置失败，请重试！')
        }
      } catch (e) {
        console.log(e.message)
        this.$Message.error('保存配置失败，请重试！')
      }
    },
    // 选择左侧开关
    selectSwitch (index) {
      this.data[this.current].listswitch = index
      this.$forceUpdate()
    },
    /**
     * 计算客服用户详情
     */
    calcUsers (list) {
      var statis = {}
      list.forEach(function (item) {
        if (item.subscribe) {
          statis.subscribe = statis.subscribe || 0
          statis.subscribe += 1
          if (item.groupid) {
            statis.groupid = statis.groupid || 0
            statis.groupid += 1
          } else {
            statis.ungroupid = statis.ungroupid || 0
            statis.ungroupid += 1
          }
        } else {
          statis.unsubscribe = statis.unsubscribe || 0
          statis.unsubscribe += 1
        }
      })
      statis.groupid = statis.groupid || 0
      statis.subscribe = statis.subscribe || 0
      statis.ungroupid = statis.ungroupid || 0
      statis.unsubscribe = statis.unsubscribe || 0
      return statis
    },
    // 加载登录资源
    async loadingRes (csid) {
      if (!csid) return
      try {
        var datas = {
          currentuser: 0,
          listswitch: 0,
          userload: false,
          csuser: {},
          alluser: [],
          msguser: {},
          statis: {},
          settingbox: {
            isopen: false,
            index: 1
          },
          massmsg: false
        }
        // 1.设置客服账号
        var csuser = await this.$fn.getCuUser(csid)
        if (csuser.status !== 1) throw new Error('登录失败，请重试！')
        await this.$fn.setUsetType(1, csid)
        csuser.cs_info.type = 1
        datas.csuser = csuser.cs_info
        // 2.获取更新消息列表
        var msguser = await this.$fn.getMsguser(csid)
        msguser.sort(function (v1, v2) {
          return v1.last_butt_time - v2.last_butt_time
        }).reverse()
        datas.msguser = msguser
        // 3.获取用户列表
        var allUser = await this.$fn.getAlluser(csid)
        if (allUser.status !== 1) allUser.msg = []
        datas.statis = this.calcUsers(allUser.msg)
        datas.alluser = allUser.msg
        this.data[csid] = datas
        // 4.链接socket
        window.$Index.$ws.emit('re_connect', { // 链接socket.io
          user: this.data[csid].csuser,
          type: 1002
        })
        this.$forceUpdate()
        return {
          status: 1,
          msg: '资源加载完成',
          data: this.data[csid]
        }
      } catch (e) {
        console.log(e)
        return {
          status: -1,
          msg: e.message
        }
      }
    },
    // 点击消息列表
    msgClick (user) {
      this.$emit('clearNewnum', this.current, user)
      if (this.data[this.current].currentuser.id === user.id) return
      this.$electron.ipcRenderer.send('main_click_userchat', user.id)
      this.$emit('clearNewnum', this.current, user)
      this.data[this.current].userload = true
      this.data[this.current].currentuser = user
      this.data[this.current].msguser.forEach(item => {
        if (item.user_id === user.id) {
          item.new_msg_num = 0
          this.$refs['msguser_list'] && this.$refs['msguser_list'].refreshData()
        }
      })
      // setTimeout(() => {
      //   this.data[this.current].userload = false
      //   this.$forceUpdate()
      // }, 1000)
      this.$forceUpdate()
    },
    // 给用户发送消息
    sendUserMsg (msg, userId, index) {
      // this.$fn.sendMsgs(this, msg, userId, index)
    },
    // 更新消息列表的用户
    updataMsgUser (msg, type) {
      if (type === 1) { // 客服主动发送消息
        this.data[msg.cs_id].alluser.forEach(function (item) {
          if (msg.openid === item.openid) {
            item.groupid = 1
          }
        })
      }
      this.data[msg.cs_id].statis = this.calcUsers(this.data[msg.cs_id].alluser)
      this.$forceUpdate()
      this.$refs.alluser_list && this.$refs.alluser_list.$forceUpdate()
      var _inmsgList = false
      this.data[msg.cs_id].msguser.forEach((item, index) => {
        if (item.openid === msg.openid) {
          _inmsgList = true
          var arr = JSON.parse(JSON.stringify(item))
          arr.last_butt_time = msg.send_time
          arr.last_butt_msg = msg.type === 'text' ? msg.content
            : msg.type === 'image' ? '[图片]'
              : msg.type === 'image' ? '[图片]' : '[新消息]'
          this.$set(this.data[msg.cs_id].msguser, index, arr)
          this.$refs.msguser_list && this.$refs.msguser_list.$forceUpdate()
        }
      })
      if (!_inmsgList) {
        // 不在消息列表里面
        this.data[msg.cs_id].alluser.forEach((item) => {
          if (msg.openid === item.openid) {
            var arr = JSON.parse(JSON.stringify(item))
            arr.last_butt_time = msg.send_time
            arr.last_butt_msg = msg.type === 'text' ? msg.content
              : msg.type === 'image' ? '[图片]'
                : msg.type === 'image' ? '[图片]' : '[新消息]'
            this.data[msg.cs_id].msguser.push(arr)
            this.$refs.msguser_list && this.$refs.msguser_list.$forceUpdate()
          }
        })
      }
      this.sortMsgList(msg.cs_id)
    },
    // 排序消息列表
    sortMsgList (id) {
      this.data[id].msguser.sort(function (x, y) {
        let v1 = y.last_butt_time || 0
        let v2 = x.last_butt_time || 0
        return v1 - v2
      })
      this.$refs.msguser_list && this.$refs.msguser_list.$forceUpdate()
    },
    // 刷新客服窗口
    refresh (id) {
      var data = {
        alluser: [],
        csuser: {},
        currentuser: 0,
        listswitch: 0,
        msguser: [],
        statis: {}
      }
      this.$set(this.data, id, data)
      this.loadingRes(id)
    },
    // 打开设置窗口
    async openSetBox () {
      this.data[this.current].settingbox.isopen = true
      var timeout
      try {
        var result = await this.$http.post(this.$store.state.Config.base_url + '/gettimeout', {cs_id: this.data[this.current].csuser.id})
        if (result.data.status === 1) {
          timeout = {
            isinure: result.data.arr.isinure,
            timeout: result.data.arr.timeout / 1000
          }
        }
        var csuser = await this.$fn.getCuUser(this.data[this.current].csuser.id)
        if (result.status === 1) {
          Object.assign(this.data[this.current].csuser, csuser)
        }
        var config = await this.$db.config.getConfig()
        this.config = config
        var checkVersion = await this.$fn.getVersion()
        if (checkVersion.status === 1) {
          this.newVersion = {
            incheck: true,
            data: checkVersion.news
          }
        } else {
          this.newVersion = {
            incheck: false
          }
        }
      } catch (e) {
        console.log(e)
        timeout = {}
      }
      this.data[this.current].settingbox.replymsg = {
        reply_text: this.data[this.current].csuser.auto_reply_text,
        reply_img: this.data[this.current].csuser.auto_reply_img
      }
      Object.assign(this.data[this.current].settingbox.replymsg, timeout)
      this.$forceUpdate()
    },
    // 改变设置窗口显示状态
    changeSetBox () {
      window.reply_pic = null
      this.$forceUpdate()
    },
    // 选择设置项目
    selectSetItem (index) {
      this.data[this.current].settingbox.index = index
      this.$forceUpdate()
    },
    // 保存离线超时时间
    async settimeout () {
      var datas = {
        cs_id: this.current,
        isinure: this.data[this.current].settingbox.replymsg.isinure,
        timeout: parseInt(this.data[this.current].settingbox.replymsg.timeout) * 1000
      }
      try {
        var result = await this.$http.post(this.$store.state.Config.base_url + '/settimeout', datas)
        if (result.data.status === 1) {
          this.$Message.success('设置成功')
        } else {
          this.$Message.error('设置失败')
        }
      } catch (e) {
        this.$Message.error('设置失败')
      }
    },
    // 上传图片
    uploadReplypic () {
      var _this = this
      var fileIndex = document.createElement('input')
      fileIndex.setAttribute('type', 'file')
      fileIndex.onchange = function () {
        var file = this.files[0]
        if (file.type === 'image/jpeg' || file.type === 'image/gif' || file.type === 'image/png') {
          if (file.size < 2097152) {
            window.reply_pic = file
            _this.data[_this.current].settingbox.replymsg.reply_img = _this.$fn.getObjectURL(file)
            _this.$forceUpdate()
          } else {
            _this.$Message.warning('图片太大了，请选择2M以内的图片')
          }
        } else {
          _this.$Message.warning('请选择支持的图片格式')
        }
      }
      fileIndex.click()
    },
    // 设置离线回复
    async saveReplyMsg () {
      if (this.data[this.current].settingbox.replymsg.reply_text === this.data[this.current].csuser.auto_reply_text) {
        if (this.data[this.current].settingbox.replymsg.reply_img === this.data[this.current].csuser.auto_reply_img) {
          return
        }
      }
      if (window.reply_pic) {
        this.$Message.loading({
          content: '正在上传图片',
          duration: 0
        })
        try {
          var image = await this.$fn.uploadImage(window.reply_pic)
          this.$Message.destroy()
          if (image.error === 0) {
            this.data[this.current].settingbox.replymsg.reply_img = image.url
            this.$Message.destroy()
            this.$forceUpdate()
          } else {
            throw new Error('上传图片失败!')
          }
        } catch (e) {
          console.log(e)
          this.$Message.destroy()
          this.$Message.error('上传图片失败')
        }
      }
      this.$Message.loading({
        content: '正在保存...',
        duration: 0
      })
      var data = {
        id: this.current,
        auto_reply_text: this.data[this.current].settingbox.replymsg.reply_text,
        auto_reply_img: this.data[this.current].settingbox.replymsg.reply_img
      }
      try {
        var result = await this.$fn.saveReplyMsg(data)
        if (result.status !== 1) {
          throw new Error('保存失败!')
        }
        this.$Message.destroy()
        this.data[this.current].csuser.auto_reply_text = data.auto_reply_text
        this.data[this.current].csuser.auto_reply_img = data.auto_reply_img
        this.$forceUpdate()
        this.$Message.success('保存成功')
      } catch (e) {
        console.log(e)
        this.$Message.destroy()
        this.$Message.error('保存失败')
      }
    },
    // 设置客服在现状态
    async setUsetType (type, csid) {
      if (type === this.data[csid || this.current].csuser.type) return
      try {
        var result = await this.$fn.setUsetType(type, csid || this.current)
        if (result.status !== 1) {
          this.data[csid || this.current].csuser.type = type
          throw new Error('设置失败!')
        }
        this.data[csid || this.current].csuser.type = type
        this.$Message.success('设置成功')
      } catch (e) {
        this.$Message.error('设置失败')
      }
      this.$forceUpdate()
      this.$refs['csuser_info'].$forceUpdate()
    },
    // 打开群发面板
    openMassbox () {
      this.data[this.current].massmsg = true
      this.$forceUpdate()
    },
    // 打开群发面板
    closeMassbox () {
      this.data[this.current].massmsg = false
      this.$forceUpdate()
    },
    // 设置用户信息
    async setUserinfo (user) {
      // 修改消息列表里面的
      // this.data[this.current].msguser
      for (var i = this.data[this.current].msguser.length - 1; i >= 0; i--) {
        if (user.user_id === this.data[this.current].msguser[i].user_id) {
          var obj = Object.assign(this.data[this.current].msguser[i], user)
          this.$forceUpdate()
          this.$refs['msguser_list'].$forceUpdate()
          this.$refs['msguser_list'].$refs['user_item'].forEach((item) => { item.$forceUpdate() })
          this.$db.user_list.addUser(obj)
        }
      }
      // this.data[this.current].msguser
      for (var j = this.data[this.current].alluser.length - 1; j >= 0; j--) {
        if (user.user_id === this.data[this.current].alluser[j].user_id) {
          Object.assign(this.data[this.current].alluser[j], user)
          this.$forceUpdate()
        }
      }
    }
  }
}
</script>

<style lang="less">
@import './style.less';
</style>
